package com.heima.appgateway.filter;

import com.heima.appgateway.utils.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 认证过滤器
 *
 * @author liudo
 * @version 1.0
 * @project heima-leadnews
 * @date 2023/11/3 15:11:50
 */
@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {
    private static final String TOKEN = "Token";
    private static final String LOGIN_PATH = "/user/api/v1/login/login_auth";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 当前的请求如果是登录 则放行
        if (request.getPath().toString().contains(LOGIN_PATH)) {
            return chain.filter(exchange);
        }
        // 校验token这个请求头
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(TOKEN);
        // jwt是否合法  // 不合法 401
        if (StringUtils.isEmpty(token) || !AppJwtUtil.verifyToken(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 合法 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
